# -*- coding: utf-8 -*-

import socket,time,json,random,string,sys,os

ROOT=os.path.abspath(os.path.dirname(os.path.abspath(__file__))+"/../")
sys.path.append(os.path.abspath(ROOT+"/libs"))

from common import *
'''
通过sendto()给服务器发数据：
'''
conf={}
confPath=ROOT+"/conf/conf.json"
with open(confPath,"r") as f:
    conf=json.load(f)
key=conf["key"]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
PORT = conf["udp_port"]
network = '<broadcast>'
# 发送数据:
nonce=randStr(9)
ts=str(int(time.time()))
msgDict={"n":nonce,"t":ts,"s":hash(key,ts,nonce)}


if len(sys.argv)>1:
    msgDict['c']=str.join(" ",sys.argv[1:])

msg=json.dumps(msgDict)
s.sendto(msg.encode("utf-8"), (network, PORT))
if 'c' in msgDict:
    echo,addr=s.recvfrom(4096)
    print(echo)
    info(addr)
s.close()
